package com.youlu.campus.admin.group.service.impl;

import com.youlu.campus.admin.base.BaseService;
import com.youlu.campus.admin.community.entity.CommContent;
import com.youlu.campus.admin.group.dto.GroupQueryRequest;
import com.youlu.campus.admin.group.dto.GroupRequest;
import com.youlu.campus.admin.group.dto.GroupResponse;
import com.youlu.campus.admin.group.entity.GroupLogPO;
import com.youlu.campus.admin.group.entity.GroupPO;
import com.youlu.campus.admin.group.service.GroupService;
import com.youlu.campus.admin.user.entity.GroupMemberPO;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.base.group.enums.GroupStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 小组管理接口实现类
 * @author: YangJ
 * @date: 2020/12/29 10:08
 */
@Slf4j
@Service("groupService")
public class GroupServiceImpl extends BaseService implements GroupService {

    @Override
    public Page<GroupResponse> list(GroupQueryRequest request) {
        Query query = new Query();
        if (StringUtils.isNotBlank(request.getKey())) {
            Pattern pattern = Pattern.compile("^.*" + request.getKey() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(new Criteria().orOperator(Criteria.where("id").is(request.getKey()),
                    Criteria.where("name").regex(pattern)));
        }
        if (StringUtils.isNotBlank(request.getStatus())) {
            query.addCriteria(Criteria.where("status").is(request.getStatus()));
        }
        if (StringUtils.isNotBlank(request.getUniversityName())) {
            Pattern pattern = Pattern.compile("^.*" + request.getUniversityName() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("universityName").regex(pattern));
        }
        if (Objects.nonNull(request.getStartTime()) && Objects.nonNull(request.getEndTime())) {
            query.addCriteria(Criteria.where("createdTime").lte(request.getEndTime()).gte(request.getStartTime()));
        } else if (Objects.nonNull(request.getStartTime())) {
            query.addCriteria(Criteria.where("createdTime").gte(request.getStartTime()));
        } else if (Objects.nonNull(request.getEndTime())) {
            query.addCriteria(Criteria.where("createdTime").lte(request.getEndTime()));
        }
        long count = mongoTemplate.count(query, GroupPO.class);
        PageRequest pageRequest = PageRequest.of(request.getPage() - 1, request.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<GroupPO> groupPOList = mongoTemplate.find(query.with(pageRequest), GroupPO.class);
        List<GroupResponse> list = groupPOList.stream().map(groupPO -> {
            GroupResponse response = mapperFacade.map(groupPO,GroupResponse.class);
            response.setContentCount(queryContentCount(response.getId()));
            return response;
        }).collect(Collectors.toList());
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }

    @Override
    public boolean dissolution(GroupRequest request) {

        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(request.getId()));
        GroupPO groupPO = mongoTemplate.findOne(query, GroupPO.class);
        if (groupPO == null){
            throw new BusinessException("未查询到小组！");
        }
        groupPO.setStatus(GroupStatusEnum.DISSOLUTION.getValue());
        groupPO.setDissolutionReason("后台人工解散");
        groupPO.setDeleted(true);
        groupPO.setUpdatedTime(new Date());
        mongoTemplate.save(groupPO);
        //小组成员设置成无效
        this.removeGroupMembers(groupPO.getId());
        //日志
        GroupLogPO logPO = new GroupLogPO();
        logPO.setUserId(request.getUserId());
        logPO.setGroupId(groupPO.getId());
        logPO.setReason(request.getReason());
        logPO.setType("dissolution");
        logPO.setCreatedTime(new Date());
        mongoTemplate.save(logPO);

        return true;
    }

    private Long queryContentCount(String groupId){

        Query query = new Query();
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("userGroupId").is(groupId));
        return mongoTemplate.count(query, CommContent.class);

    }

    private void removeGroupMembers(String groupId) {
        //小组成员设置成无效
        Query query = new Query();
        query.addCriteria(Criteria.where("groupId").is(groupId));
        query.addCriteria(Criteria.where("deleted").is(false));
        Update update = new Update();
        update.set("updatedTime", new Date());
        update.set("deleted", true);
        mongoTemplate.updateMulti(query, update, GroupMemberPO.class);
    }
}
